package com.hjt.zhibo.tools;

import java.util.List;

import jodd.util.StringUtil;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.search.Attribute;
import net.sf.ehcache.search.Direction;
import net.sf.ehcache.search.Query;
import net.sf.ehcache.search.Result;
import net.sf.ehcache.search.Results;

public class EncacheTools {

	private static final String configPath =  "src/config/ehcache.xml";
	private CacheManager cacheManager;
	
	//private final int cacheLimit = 10000000;
	
	private volatile static EncacheTools encacheTools;
	
	
	private EncacheTools(String configPath){
			cacheManager = new CacheManager(configPath);  
	}
	
	public static EncacheTools getInstance(){
		if(encacheTools == null){
			 synchronized(EncacheTools.class){
				 if (encacheTools == null)
				  encacheTools = new EncacheTools(configPath); 
				}
		}
		return encacheTools;
	}
	
	public Cache getCache(String cacheName){
		return cacheManager.getCache(cacheName);
	}
	
	public void putCache(String cacheName, Object key, Object value){
		
		Cache cache = cacheManager.getCache(cacheName);
		if(cache == null){
			System.out.println("未找到缓存名称...");
			return ;
		}
		
		cache.put(new Element(key, value));
	}
	
	public Object getElement(String cacheName, Object key){
		Cache cache = cacheManager.getCache(cacheName);
		if(cache != null){
			Element element = cache.get(key);
			return element == null ? null : element.getObjectValue();
		}
		return null;
	}
	
	public List<Result> getRoomList(String key, int pageNum, int pageCount){
		Cache cache = cacheManager.getCache("room");
		if(cache != null){
			Query query = cache.createQuery().includeValues();
			
			Attribute<String> countAttribute = cache.getSearchAttribute("count");
			
			if(StringUtil.isNotBlank(key)){
				Attribute<String> roomNameAttribute = cache.getSearchAttribute("roomName");
				Attribute<String> authAttribute = cache.getSearchAttribute("auth");
				query.addCriteria(roomNameAttribute.ilike("*"+key+"*").or(authAttribute.ilike("*"+key+"*"))).addOrderBy(countAttribute, Direction.ASCENDING);
			} else{
				query.addOrderBy(countAttribute, Direction.ASCENDING);
			}
			
			Results results = query.execute();
			List<Result> list = results.range(pageNum, pageCount);
			results.discard();
			return list;
		}
		return null;
	}
	
}
